/**
 * 管理机
 */
import "reflect-metadata";
import "./common";
/**
 * 引入公共文件
 */
/**
 * 管理机的主要职责是 管理本脚本下的所有任务
 * 1. 管理UI任务
 * 2. 管理脚本任务
 * 3. 务必轻量
 */
import { container as injector } from 'tsyringe'
import { Sender } from "./autox/sender";
import { httpGetAsync } from "./autox/http";
import { Timer } from "./autox/timer";
import { sendToWebsocket } from "./utils/send";

const sender = injector.resolve(Sender)
const timer = injector.resolve(Timer)
timer.setInterval(() => { }, 1000 * 10)
sender.on('DOWNLOAD_FROM_URL', (payload: any) => {
    try {
        downloadUrl(payload.url, payload.path)
    } catch (e) {
        toastLog(`从远程下载文件失败: ${e.message}`)
    }
})
sender.on('DOWNLOAD_FROM_CODE', (payload: any) => {
    try {
        downloadCode(payload.path, payload.code)
    } catch (e) {
        toastLog(`保存代码失败: ${e.message}`)
    }
})
sender.on('UPLOAD_FILE_FROM_LOCAL', (payload: any) => {
    try {
        readFile(payload.path)
    } catch (e) {
        toastLog(`读取文件失败: ${e.message}`)
    }
})
function downloadUrl(url: string, path: string) {
    const response = httpGetAsync(url)
    const js = response.body.string()
    files.write(files.cwd() + '/' + path, js)
}

function downloadCode(path: string, code: string) {
    files.write(files.cwd() + '/' + path, code)
}

function readFile(path: string) {
    const str = files.read(files.cwd() + '/' + path)
    toastLog(`读取文件${path}成功`)
    sendToWebsocket({ type: 'UPLOAD_FILE_FROM_LOCAL', payload: { data: str, path } })
}
